# 定义变量
$INSTALL_DIR = "C:\nps"            # 安装目录
$CONFIG_FILE = "$INSTALL_DIR\npc.conf"  # 配置文件路径
$SERVICE_NAME = "npc"              # 服务名称
$SCRIPT_NAME = "NPS"               # 脚本命令名称
$SCRIPT_INSTALL_DIR = "C:\Windows\System32"  # 脚本安装目录

# 检查是否以管理员身份运行
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "请以管理员身份运行此脚本"
    exit 1
}

# 获取系统架构
$ARCH = (Get-WmiObject Win32_Processor).AddressWidth
if ($ARCH -eq 64) {
    $ARCH = "amd64"
} elseif ($ARCH -eq 32) {
    $ARCH = "386"
} else {
    Write-Host "不支持的架构: $ARCH"
    exit 1
}

# 获取最新版本
function Get-LatestVersion {
    $LATEST_VERSION = (Invoke-WebRequest -Uri "https://api.github.com/repos/djylb/nps/releases/latest" -UseBasicParsing | ConvertFrom-Json).tag_name
    if (-not $LATEST_VERSION) {
        Write-Host "无法获取最新版本，请检查网络连接"
        exit 1
    }
    return $LATEST_VERSION
}

# 安装NPC客户端
function Install-Npc {
    $LATEST_VERSION = Get-LatestVersion
    Write-Host "正在下载NPC客户端（版本: $LATEST_VERSION, 架构: $ARCH）..."

    # 确保安装目录存在
    if (-not (Test-Path $INSTALL_DIR)) {
        New-Item -ItemType Directory -Path $INSTALL_DIR | Out-Null
    }

    $DOWNLOAD_URL = "https://github.com/djylb/nps/releases/download/$LATEST_VERSION/windows_${ARCH}_client.zip"
    Write-Host "下载链接: $DOWNLOAD_URL"

    # 下载文件
    Invoke-WebRequest -Uri $DOWNLOAD_URL -OutFile "$INSTALL_DIR\npc.zip"
    if (-not $?) {
        Write-Host "下载失败，请检查网络连接或下载链接是否正确"
        exit 1
    }

    # 解压文件
    Write-Host "正在解压文件..."
    Expand-Archive -Path "$INSTALL_DIR\npc.zip" -DestinationPath $INSTALL_DIR -Force
    Remove-Item -Path "$INSTALL_DIR\npc.zip" -Force

    # 检查文件
    if (-not (Test-Path "$INSTALL_DIR\npc.exe")) {
        Write-Host "解压后未找到 npc.exe 文件，请检查压缩包内容"
        exit 1
    }

    Write-Host "NPC客户端安装完成！"
}

# 初始化配置文件
function Init-Config {
    while ($true) {
        $NPS_SERVER = Read-Host "请输入NPS服务器地址和端口（例如 127.0.0.1:8024）"
        if (-not $NPS_SERVER) {
            Write-Host "输入不能为空，请重新输入！"
        } else {
            break
        }
    }

    while ($true) {
        $CONN_TYPE = Read-Host "请输入连接类型（默认 tcp）"
        if (-not $CONN_TYPE) {
            $CONN_TYPE = "tcp"  # 如果用户未输入，则使用默认值 tcp
        }
        if (-not $CONN_TYPE) {
            Write-Host "输入不能为空，请重新输入！"
        } else {
            break
        }
    }

    while ($true) {
        $NPS_VKEY = Read-Host "请输入客户端密钥"
        if (-not $NPS_VKEY) {
            Write-Host "输入不能为空，请重新输入！"
        } else {
            break
        }
    }

    # 写入配置文件
    @"
[common]
server_addr=$NPS_SERVER
conn_type=$CONN_TYPE
vkey=$NPS_VKEY
"@ | Out-File -FilePath $CONFIG_FILE -Encoding ASCII

    Write-Host "配置文件已初始化: $CONFIG_FILE"
}

# 创建Windows服务
function Create-Service {
    Write-Host "正在创建Windows服务..."
    $SERVICE_EXE = "$INSTALL_DIR\npc.exe"
    $SERVICE_DISPLAY_NAME = "NPC Client (npc)"
    $SERVICE_DESCRIPTION = "NPC Client (npc)"

    # 创建服务
    New-Service -Name $SERVICE_NAME -BinaryPathName "`"$SERVICE_EXE`" -config=`"$CONFIG_FILE`"" -DisplayName $SERVICE_DISPLAY_NAME -Description $SERVICE_DESCRIPTION -StartupType Automatic | Out-Null
    if (-not $?) {
        Write-Host "服务创建失败，请检查日志"
        exit 1
    }

    Write-Host "Windows服务已创建！"
}

# 启动服务并检查状态
function Start-Service {
    Write-Host "正在启动 NPC 客户端服务..."
    Start-Service -Name $SERVICE_NAME
    if (-not $?) {
        Write-Host "服务启动失败，请检查日志"
        Get-EventLog -LogName Application -Source $SERVICE_NAME -Newest 10
        Read-Host "按 Enter 键返回菜单..."
        return  # 返回菜单
    }

    Write-Host "正在检查服务状态..."
    Get-Service -Name $SERVICE_NAME

    # 检查客户端日志
    Write-Host "正在检查客户端日志..."
    if (Test-Path "$INSTALL_DIR\logs\npc.log") {
        Get-Content "$INSTALL_DIR\logs\npc.log"
    } else {
        Write-Host "未找到客户端日志文件"
    }

    Read-Host "按 Enter 键返回菜单..."
}

# 卸载NPC客户端
function Uninstall-Npc {
    Write-Host "正在停止 NPC 客户端服务..."
    Stop-Service -Name $SERVICE_NAME -Force
    Set-Service -Name $SERVICE_NAME -StartupType Disabled

    Write-Host "正在删除服务..."
    Remove-Service -Name $SERVICE_NAME

    Write-Host "正在删除安装目录..."
    Remove-Item -Path $INSTALL_DIR -Recurse -Force

    Write-Host "NPC客户端已卸载！"
}

# 显示菜单
function Show-Menu {
    Write-Host "请选择要执行的操作："
    Write-Host "1. 安装NPC客户端"
    Write-Host "2. 更改服务器地址"
    Write-Host "3. 更改客户端密钥"
    Write-Host "4. 重启NPC客户端"
    Write-Host "5. 卸载NPC客户端"
    Write-Host "6. 卸载脚本和NPC客户端"
    Write-Host "0. 退出"
}

# 更改服务器地址和端口
function Change-Server {
    while ($true) {
        $NEW_SERVER = Read-Host "请输入新的服务器地址和端口（例如 127.0.0.1:8024）"
        if (-not $NEW_SERVER) {
            Write-Host "输入不能为空，请重新输入！"
        } else {
            break
        }
    }

    # 更新配置文件
    (Get-Content $CONFIG_FILE) -replace "^server_addr=.*", "server_addr=$NEW_SERVER" | Set-Content $CONFIG_FILE
    Write-Host "服务器地址和端口已更新为: $NEW_SERVER"

    # 重启服务
    Restart-Service -Name $SERVICE_NAME
    if ($?) {
        Write-Host "NPC客户端已重启，更改成功！"
    } else {
        Write-Host "NPC客户端重启失败，请检查日志"
    }

    Read-Host "按 Enter 键返回菜单..."
}

# 更改客户端密钥
function Change-Vkey {
    while ($true) {
        $NEW_VKEY = Read-Host "请输入新的客户端密钥"
        if (-not $NEW_VKEY) {
            Write-Host "输入不能为空，请重新输入！"
        } else {
            break
        }
    }

    # 更新配置文件
    (Get-Content $CONFIG_FILE) -replace "^vkey=.*", "vkey=$NEW_VKEY" | Set-Content $CONFIG_FILE
    Write-Host "客户端密钥已更新为: $NEW_VKEY"

    # 重启服务
    Restart-Service -Name $SERVICE_NAME
    if ($?) {
        Write-Host "NPC客户端已重启，更改成功！"
    } else {
        Write-Host "NPC客户端重启失败，请检查日志"
    }

    Read-Host "按 Enter 键返回菜单..."
}

# 重启NPC客户端
function Restart-Npc {
    Restart-Service -Name $SERVICE_NAME
    if ($?) {
        Write-Host "NPC客户端已重启，操作成功！"
    } else {
        Write-Host "NPC客户端重启失败，请检查日志"
    }

    Read-Host "按 Enter 键返回菜单..."
}

# 安装脚本到系统
function Install-Script {
    Write-Host "正在安装脚本到系统..."
    Copy-Item -Path $MyInvocation.MyCommand.Path -Destination "$SCRIPT_INSTALL_DIR\$SCRIPT_NAME.ps1" -Force
    Write-Host "脚本已安装，您可以通过命令 '$SCRIPT_NAME' 来运行脚本。"
}

# 卸载脚本和NPC客户端
function Uninstall-ScriptAndNpc {
    Write-Host "正在卸载脚本和NPC客户端..."
    Uninstall-Npc
    Remove-Item -Path "$SCRIPT_INSTALL_DIR\$SCRIPT_NAME.ps1" -Force
    Write-Host "脚本和NPC客户端已卸载！"
}

# 主循环
function Main {
    while ($true) {
        Show-Menu
        $OPTION = Read-Host "请输入选项（1-6，0 退出）"
        switch ($OPTION) {
            1 {
                Install-Npc
                Init-Config
                Create-Service
                Start-Service
                Set-Service -Name $SERVICE_NAME -StartupType Automatic
                Install-Script
            }
            2 {
                Change-Server
            }
            3 {
                Change-Vkey
            }
            4 {
                Restart-Npc
            }
            5 {
                Uninstall-Npc
            }
            6 {
                Uninstall-ScriptAndNpc
            }
            0 {
                Write-Host "退出"
                break
            }
            default {
                Write-Host "无效选项，请重新输入"
            }
        }
    }
}

# 如果直接运行脚本，则进入菜单
if ($MyInvocation.InvocationName -ne "&") {
    Main
}